//改变地图底图
function changeBaseMap(viewer, basemapname){
    if(basemapname === '高德卫图'){
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
        viewer.imageryLayers.addImageryProvider(
        new  Cesium.UrlTemplateImageryProvider({
            maximumLevel:18,//最大缩放级别
            url : 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
            style: "default",
            format: "image/png",
            tileMatrixSetID: "GoogleMapsCompatible"
        })
        )
    }
    else if(basemapname === '天地图卫图'){
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
        const tdtToken = '6cbed5655e7478e21ae0f099d467f39b' // 填入你创建的天地图Token
        viewer.imageryLayers.addImageryProvider(
        new  Cesium.WebMapTileServiceImageryProvider({
            url: `http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=${tdtToken}`,
            layer: "tdtBasicLayer",
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",
        })
        )
    }
    else if(basemapname === '天地图电子地图'){
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
        viewer.imageryLayers.addImageryProvider(
        new  Cesium.WebMapTileServiceImageryProvider({
            url: "http://{s}.tianditu.gov.cn/vec_c/wmts?service=wmts&request=GetTile&version=1.0.0" +
                "&LAYER=vec&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}" +
                "&style=default&format=tiles&tk=6cbed5655e7478e21ae0f099d467f39b",
            layer: "tdtCva",
            style: "default",
            format: "tiles",
            tileMatrixSetID: "c",
            subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
            tilingScheme: new Cesium.GeographicTilingScheme(),
            tileMatrixLabels: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
            maximumLevel: 18,
            show: false
        })
        )
        // 下面是天地图注记
        viewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
            url:
            "http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=6cbed5655e7478e21ae0f099d467f39b",
            layer: "tiandituImgMarker",
            style: "default",
            format: "image/jpeg",
            tileMatrixSetID: "tiandituImgMarker",
            show: true,
            maximumLevel: 16
        })
        )
    }
    else if(basemapname === 'ArcGIS卫图'){
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0))
        viewer.imageryLayers.addImageryProvider(
            new  Cesium.ArcGisMapServerImageryProvider({
                url:'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
                baseLayerPicker : false
            })
        )
    }
}

//绑定鼠标事件，点击获取经纬度
function addmouseClickEvent(viewer, div) {
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    //监听鼠标点击,拿到坐标点位置
    handler.setInputAction(function (event) {
        // 转换为不包含地形的笛卡尔坐标
        // 注意下面这句话与鼠标移动不同
        let position = viewer.scene.camera.pickEllipsoid(event.position);
        if(!position) return

        // 转经纬度（弧度）坐标
        let radiansPos = Cesium.Cartographic.fromCartesian(position);      
        //转为经纬度
        let pickedFeature = viewer.scene.pick(event.position);
        let x  = Cesium.Math.toDegrees(radiansPos.longitude) - 0
        let y  = Cesium.Math.toDegrees(radiansPos.latitude) - 0
        // console.log(x,y)
        div.innerHTML = `${x.toFixed(3)},${y.toFixed(3)}`
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

//绑定鼠标事件，移动获取经纬度
function addmouseMoveEvent(viewer, div) {
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    //监听鼠标点击,拿到坐标点位置
    handler.setInputAction(function (event) {
        // 转换为不包含地形的笛卡尔坐标
        // 注意下面这句话与鼠标点击不同
        let position = viewer.scene.camera.pickEllipsoid(event.endPosition);
        if(!position) return

        // 转经纬度（弧度）坐标
        let radiansPos = Cesium.Cartographic.fromCartesian(position);      
        //转为经纬度
        let x  = Cesium.Math.toDegrees(radiansPos.longitude) - 0
        let y  = Cesium.Math.toDegrees(radiansPos.latitude) - 0
        div.innerHTML = `${x.toFixed(3)},${y.toFixed(3)}`
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}

//开始鼠标点击画点
function startMouseClickDrawPoint(viewer, drawPoints){
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    //监听鼠标点击,拿到坐标点位置
    handler.setInputAction(function (event) {
        // 转换为不包含地形的笛卡尔坐标
        let position = viewer.scene.camera.pickEllipsoid(event.position);
        if(!position) return

        // 转经纬度（弧度）坐标
        let radiansPos = Cesium.Cartographic.fromCartesian(position);      
        //转为经纬度
        let x  = Cesium.Math.toDegrees(radiansPos.longitude) - 0
        let y  = Cesium.Math.toDegrees(radiansPos.latitude) - 0

        drawPoints.push(viewer.entities.add({
            position: new Cesium.Cartesian3.fromDegrees( x, y, 0),
            point: {
                pixelSize: 20,
                color: new Cesium.Color.fromCssColorString ('#ffffff')
            }
        }))
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    return handler
}

//移除鼠标点击事件
function removeMouseClickEvent(handler){
    //移除事件
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

//开始鼠标点击选点获取点的属性
function selectPointOnMap(viewer, dataSourcesName, span){
    let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (event) { 
        //点击选中的要素
        let pickedFeature = viewer.scene.pick(event.position);
        
        if (typeof (pickedFeature) != "undefined"){ //鼠标是否点到图层上
            //获取每个点的name，判断点击的要素是否为目标图层
            const name = pickedFeature.id.name;  
            if(name === 'testPoint'){
                let en = viewer.dataSources.
                    getByName(dataSourcesName)[0].
                    entities.getById(pickedFeature.id.id)
                span.innerHTML = en.properties['名字'].getValue()
            }     
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    return handler
}
